<template>
  <div class="wrap">
    <h1>嗨购后台管理系统</h1>
    <el-form :model="form">
      <el-form-item>
        <el-input
          v-model="form.name"
          placeholder="请输入用户名"
          prefix-icon="User"
        />
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="form.password"
          placeholder="请输入密码"
          prefix-icon="Lock"
          type="password"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="width: 100%" @click="login"
          >登录</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from "axios";
import { ElMessage } from "element-plus";

import { mapMutations } from "vuex";

export default {
  data() {
    return {
      form: {
        name: "",
        password: "",
      },
    };
  },
  methods: {
    ...mapMutations("home", ["changeName"]),
    login() {
      // this.$router.push("/home");
      // console.log(this.form);
      axios
        .post("http://121.89.205.189:3000/admin/admin/login", {
          adminname: this.form.name,
          password: this.form.password,
        })
        .then((response) => {
          // console.log(response);
          if (response.data.code === "200") {
            ElMessage({
              message: "登录成功",
              type: "success",
            });

            this.changeName({ name: response.data.data.adminname });
            localStorage.setItem("adminname", response.data.data.adminname);

            localStorage.setItem("token", response.data.data.token);
            // localStorage.setItem("role", response.data.data.role);
            localStorage.setItem(
              "keys",
              JSON.stringify(response.data.data.checkedkeys)
            );

            // 理论来说，可以不需要在路由表里面写死，通过checkedkeys和addRoute方法去动态地添加路由
            // response.data.data.checkedkeys.forEach((item) => {
            //   this.$router.addRoute();
            // });

            // 动态地去添加路由
            // 场景：用于权限的控制
            // this.$router.addRoute({
            //   path: "/mine",
            //   component: () => import("../mine/Index.vue"),
            // });
            this.$router.push("/home/main");
          } else {
            ElMessage({
              message: response.data.message,
              type: "error",
            });
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
  },
};
</script>

<style scoped>
.wrap {
  width: 300px;
  margin: 200px auto;
}

h1 {
  font-size: 24px;
  text-align: center;
  margin: 20px 0;
}
</style>
